'''

Created on 2015-01-25
@author: Grammy Jiang
Version: 0.0.4

'''

import os
import re
import sys

# Report List
List_ReportName = ['ATTN', # Simulation Messages For Review HVAC
                   
                   'BEPS', # Building Energy Performance
                   'BEPU', # Building Utility Performance
                   
                   'ES-A', # Annual Costs and Savings
                   'ES-B', # Life-Cycle Non-Energy Costs
                   'ES-C', # Life-Cycle Investment Savings
                   'ES-D', # Energy Cost Summary
                   'ES-E', # Summary of Utility-Rate:
                   'ES-F', # Block-Charges and Ratchets for
                   
                   'EV-A', # Life-Cycle Costing Parameters
                   
                   'LS-A', # Space Peak Loads Summary
                   'LS-B', # Space Peak Load Components
                   'LS-C', # BuiLding Peak Load Components
                   'LS-D', # Building Monthly Loads Summary
                   'LS-E', # Space Monthly Load Components
                   'LS-F', # Building Monthly Load Component
                   'LS-K', # Space Input Fuels Summary
                   'LS-L', # Management and Solar Summary
                   
                   'LV-A', # General Project Parameters
                   'LV-B', # Summary of Spaces
                   'LV-C', # Details of Space
                   'LV-D', # Details of Exterior Surfaces
                   'LV-E', # Details of Underground Surfaces
                   'LV-F', # Details of Interior Surfaces
                   'LV-G', # Details of Schedules
                   'LV-H', # Details of Windows
                   'LV-I', # Details of Constructions
                   'LV-J', # Details of Building Shades
                   'LV-M', # DOE-2.2 Units Conversion Table
                   'LV-N', # Building Coordinate Geometry
                   
                   'PS-A', # Plant Energy Utilization
                   'PS-B', # Utility and Fuel Use Summary
                   'PS-C', # Equipment Loads and Energy Use
                   'PS-D', # Circulation Loop Loads
                   'PS-E', # Energy End-Use Summary for all Electric Meters
                   'PS-F', # Energy End-Use Summary for
                   'PS-H', # Loads and Energy Usage for
                   
                   'PV-A', # Plant Design Parameters
                   
                   'SS-A', # System Loads Summary for
                   'SS-B', # System Loads Summary for
                   'SS-C', # System Load Hours for
                   'SS-D', # Building HVAC Load Summary
                   'SS-E', # Building HVAC Load Hours
                   'SS-F', # Zone Demand Summary for
                   'SS-G', # Zone Loads Summary for
                   'SS-H', # System Utility Energy Use for
                   'SS-I', # Sensible/Latent Summary for
                   'SS-J', # Peak Heating and Cooling for
                   'SS-K', # Space Temperature Summary for
                   'SS-L', # Fan Electric Energy Use for
                   'SS-M', # Building HVAC Fan Elec Energy
                   'SS-N', # Relative Humidity Summary for
                   'SS-O', # Space Temperature Summary for
                   'SS-R', # Zone Performance Summary for
                   
                   'SV-A', # System Design Parameters for
                   'SV-B'] # Zone Fan Data for PIU System

def SIMSplit(SIMReport):
    # The beginning char of New Report
    Str_Anchor = ''
    # Output Buffer for Temporary Storage
    List_OutputBuffer = []
    # Contain Each Report as a List in Each Key
    Dict_SIMReport = {}
    
    Dict_SIMReport['Hourly Report'] = []
    Dict_SIMReport['Clear'] = []
    #Dict_SIMReport['']
    
    with open(SIMReport, 'r') as input:
        # read the first line and append into the Buffer
        List_OutputBuffer.append(input.readline())
        # Put all of the rest lines into a List
        List_Lines = input.readlines()
        
        for line in List_Lines:
            # Recognize the Beginning Line of Report and separate the report
            if re.search(Str_Anchor, line):
                (Str_EndOfLastReport, Str_BeginningOfNextReport) = line.split(Str_Anchor)
                List_OutputBuffer.append(Str_EndOfLastReport)
                
                if re.search('^HOURLY REPORT-', List_OutputBuffer[2]):
                    Dict_SIMReport['Hourly Report'].extend(List_OutputBuffer)
                else:
                    if List_OutputBuffer[2][8:12] not in List_ReportRemove:
                        Dict_SIMReport['Clear'].extend(List_OutputBuffer)
                        
                    # Separate Other Report into pieces, Named with report name
                    if List_OutputBuffer[2][8:12] not in Dict_SIMReport.keys():
                        Dict_SIMReport[List_OutputBuffer[2][8:12]] = []
                        
                        if List_OutputBuffer[2][8:12] not in List_ReportName:
                            print List_OutputBuffer[2][8:12] + " is not in the list of reports."
                            
                    Dict_SIMReport[List_OutputBuffer[2][8:12]].extend(List_OutputBuffer)
                
                # Clear the previous Temporary Storage, and start a new one
                List_OutputBuffer = []
                List_OutputBuffer.append(Str_Anchor + Str_BeginningOfNextReport)
            else:
                # Store the lines as Temporary
                List_OutputBuffer.append(line)
                
    return Dict_SIMReport

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if __name__ == '__main__':
    # The Source of SIM Report
    List_SIMReport = [r'd:\Oooo\workspace\SIM Split\06 No Heating - Baseline Design.SIM']
    
    # The List of Reports to Remove
    List_ReportRemove = ['ES-A', # Annual Costs and Savings
                         'ES-B', # Life-Cycle Non-Energy Costs
                         'ES-C', # Life-Cycle Investment Savings
                         'ES-D', # Energy Cost Summary
                         'ES-E', # Summary of Utility-Rate:
                         'ES-F', # Block-Charges and Ratchets for
                         
                         'EV-A', # Life-Cycle Costing Parameters
                         
                         'LV-A', # General Project Parameters
                         'LV-B', # Summary of Spaces
                         'LV-C', # Details of Space
                         'LV-D', # Details of Exterior Surfaces
                         'LV-E', # Details of Underground Surfaces
                         'LV-F', # Details of Interior Surfaces
                         'LV-G', # Details of Schedules
                         'LV-H', # Details of Windows
                         'LV-I', # Details of Constructions
                         'LV-J', # Details of Building Shades
                         'LV-M', # DOE-2.2 Units Conversion Table
                         'LV-N'] # Building Coordinate Geometry
    
    # The List of Target Report's Names to Export
    List_TargetReport = ['ATTN', # Simulation Messages For Review LOADS
                         'BEPS', # Building Energy Performance
                         'BEPU', # Building Utility Performance
                         'LV-A', # General Project Parameters
                         'PV-A', # PV-A Plant Design Parameters
                         'SV-A'] # System Design Parameters for
    
    # Index of this SIMReport
    Int_i = 1
    # Copy of the List of SIMReport
    List_SIMReport_Available = []
    # Index of the report
    Int_j = 1
    
    if not len(List_SIMReport) == 0:
        print "Number of Reports: " + str(len(List_SIMReport))
        print "List of Reports:"
        
        for SIMReport in List_SIMReport:
            # Test File exist and access or not
            if not os.path.isfile(SIMReport):
                print "\t" + str(Int_i) + ". " + SIMReport + " (None)"
            elif not os.access(SIMReport, os.R_OK):
                print "\t" + str(Int_i) + ". " + SIMReport + " (Not Access)"
            else:
                print "\t" + str(Int_i) + ". " + SIMReport + " (Available)"
                List_SIMReport_Available.append(SIMReport)
            Int_i = Int_i + 1
            
        print "Check Done." + "\n"
        
        for SIMReport in List_SIMReport_Available:
            print "Start reading " + SIMReport
            Dict_SIMReport = SIMSplit(SIMReport)
            print "Done. Number of Reports: " + str(len(Dict_SIMReport) - 2) + "."
            
            print "Export Directory: " + os.path.dirname(SIMReport) + "\\"
            print "Start splitting and output."
            
            OutputFile = os.path.dirname(SIMReport) + '\\' + os.path.basename(SIMReport).replace(".SIM", " - Hourly Report.SIM")
            with open(OutputFile, 'w') as output:
                print "\t" + "1. Export Hourly Reports."
                output.writelines(Dict_SIMReport['Hourly Report'])
            
            OutputFile = os.path.dirname(SIMReport) + '\\' + os.path.basename(SIMReport).replace(".SIM", " - Clear Report.SIM")
            with open(OutputFile, 'w') as output:
                print "\t" + "2. Export Clear Reports."
                output.writelines(Dict_SIMReport['Clear'])
            
            print "Start outputing the seperated report."
            for Report in List_TargetReport:
                print "\t" + str(Int_j) + ". Export Report " + Report + "."
                Int_j = Int_j + 1
                OutputFile = os.path.dirname(SIMReport) + '\\' + os.path.basename(SIMReport).replace(".SIM", " - " + Report + ".SIM")
                with open(OutputFile, 'w') as output:
                    output.writelines(Dict_SIMReport[Report])
            
            Int_j = 1
            print "Splitting done.\n"